import React, { useState, useEffect } from 'react'
import { Space, Table, Button, Popconfirm, Select, Form, Input, Row, Col, DatePicker, Drawer, Tree, message ,Breadcrumb} from 'antd';
import { SettingOutlined } from '@ant-design/icons'
import menuApi from '../../apis/menus'
import moment from 'moment'
import { downloadMenuInfoApi } from '../../apis/requestFile';
export default function menu() {

  //表格标题栏
  const columns = [
    {
      title: '名称',
      dataIndex: 'title',
      key: 'title',
      fixed: 'left',
      width: 200
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 140,
      render: (record) => {
        return <i className={'iconfont iconfont-' + record} style={{ width: 15, height: 15 }} ></i>
      }
    },
    {
      title: '类型',
      dataIndex: 'type',
      render: (record) => {
        return getType(record)
      },
      width: 140
    },
    {
      title: "地址",
      dataIndex: 'path',
      width: 140,
      key: 'path',
      render: (text, record) => (
        <div style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}>
          {text}
        </div>
      ),
    },
    {
      title: 'Vue组件',
      dataIndex: 'component',
      key: 'component',
      render: (text, record) => (
        <div style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}>
          {text}
        </div>
      ),
      width: 140
    },
    {
      title: '权限',
      dataIndex: 'permission',
      key: 'permission',
      width: 140,
      render: (text, record) => (
        <div style={{ wordWrap: 'break-word', wordBreak: 'break-word' }}>
          {text}
        </div>
      ),
    },
    {
      title: '排序',
      dataIndex: 'order',
      key: 'order',
      width: 140
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime'
    },
    {
      title: '修改时间',
      dataIndex: 'modifyTime',
      key: 'modifyTime'
    },
    {
      title: '操作',
      dataIndex: '',
      render: (_, record) =>
        <i style={{ color: '#1890ff', cursor: 'pointer' }} onClick={() => showDrawer(record)}><SettingOutlined /></i>
      ,
      fixed: 'right',
    }
  ];
  //获取菜单类型样式渲染
  function getType(type) {
    if (type === '0') {
      return <span className='menuCss'>菜单</span>
    } else {
      return <span className='btnCss'>按钮</span>
    }
  }

  //初始表格内容渲染
  const param = { menuName: '', createTimeFrom: '', createTimeTo: '' }
  const [totalMenu, setTotalMenu] = useState()
  const [menuData, setMenuData] = useState([])
  useEffect(() => {
    search()
  }, [])
  function search() {
    menuApi.getRoleMenus(param).then(res => {
      console.log(res);
      setMenuData(res.data.rows.children)
      setTotalMenu(res.data.total)
    })
  }

  //选择框
  const [delInfo, setDelInfo] = useState({})
  const rowSelection = {
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      console.log(record, selected, selectedRows);
      setDelInfo(record)
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      console.log(selected, selectedRows, changeRows);
    },
  };

  //搜索及重置
  const { RangePicker } = DatePicker;
  const onFinish = (values) => {
    const param = { menuName: '', createTimeFrom: '', createTimeTo: '' }
    if (values.menuName) param.menuName = values.menuName
    if (values.createTime) {
      const createTimeFrom = moment(values.createTime[0]._d).format('YYYY-MM-DD')
      const createTimeTo = moment(values.createTime[1]._d).format('YYYY-MM-DD')
      param.createTimeFrom = createTimeFrom
      param.createTimeTo = createTimeTo
    }
    menuApi.getRoleMenus(param).then(res => {
      setMenuData(res.data.rows.children)
      setTotalMenu(res.data.total)
    })
  };
  const onFinishFailed = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  const [form] = Form.useForm()
  function reset() {
    form.resetFields()
    window.location.reload()
  }

  //删除功能
  function delMenu(delInfo) {
    menuApi.delMenu(delInfo.id).then(res => {
      message.success('删除成功')
      search()
    })
  }

  //修改菜单信息
  const [formEdit] = Form.useForm()
  const [menuTree, setMenuTree] = useState([])
  const [open, setOpen] = useState(false);
  const [parentId, setParentId] = useState([])
  const [menuId, setMenuId] = useState('')
  const [typeId, setTypeId] = useState('')
  const showDrawer = (e) => {
    console.log(e);
    console.log(typeof(e.parentId) === 'string');
    setMenuId(e.id)
    setParentId([e.parentId])
    setTypeId(e.type)
    formEdit.setFieldsValue({
      menuName: e.title,
      path: e.path,
      component: e.component,
      permission: e.permission,
      icon: e.icon,
      order: e.order,
    })
    menuApi.getRoleMenus(param).then(res => {
      setMenuTree(res.data.rows.children)
    })
    setOpen(true);
  };
  const onClose = () => {
    setOpen(false);
  };
  function onFinishEdit(values) {
    const param = {
      menuName: values.menuName,
      path: values.path,
      component: values.component,
      icon: values.icon,
      orderNum: values.order,
      perms: values.permission,
      type: typeId,
      menuId: menuId,
      parentId: parentId
    }
    menuApi.updateMenu(param).then(res => {
      message.success('修改成功')
      search()
    })
  }
  function onFinishFailedEdit(errorInfo) {
    console.log('errorInfo', errorInfo);
  }
  const onSelect = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  const onCheck = (checkedKeys, info) => {
    setParentId(checkedKeys.checked.join())
  };

  //导出excel
  const toExcel = (value) => {
    if (value === '导出excel') {
      downloadMenuInfoApi()
    }
  }

  //新增菜单
  const [addMenuId,setAddMenuId] = useState([])
  const [treeAddMenu, setTreeAddMenu] = useState([])
  const [openAddMenu, setOpenAddMenu] = useState(false);
  const showDrawerAddMenu = () => {
    menuApi.getRoleMenus(param).then(res => {
      setTreeAddMenu(res.data.rows.children)
    })
    setOpenAddMenu(true);
  };
  const onCloseAddMenu = () => {
    setOpenAddMenu(false);
  };
  const confirm = (e) => {
    console.log(e);
    showDrawerAddBtn()
  };
  const cancel = (e) => {
    console.log(e);
    showDrawerAddMenu()
  };
  function onFinishAddMenu(values) {
    console.log('success', values);
    const addMenu = {
      ...values,
      type:'0',
      parentId:addMenuId
    }
    menuApi.addMenu(addMenu).then(res =>{
      message.success('菜单添加成功')
      search()
    })
  }
  function onFinishFailedAddMenu(error) {
    console.log('error', error);
  }
  const onSelectAddMenu = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  const onCheckAddMenu = (checkedKeys, info) => {
    console.log(checkedKeys.checked);
    setAddMenuId(checkedKeys.checked.join())
  };

  //新增按钮
  const [addBtnId,setAddBtnId] = useState([])
  const [treeAddBtn, setTreeAddBtn] = useState([])
  const [openAddBtn, setOpenAddBtn] = useState(false);
  const showDrawerAddBtn = () => {
    menuApi.getRoleMenus(param).then(res => {
      setTreeAddBtn(res.data.rows.children)
    })
    setOpenAddBtn(true);
  };
  const onCloseAddBtn = () => {
    setOpenAddBtn(false);
  };
  function onFinishAddBtn(values) {
    console.log('success', values);
    menuApi.addMenu({...values,type:'1',parentId:addBtnId}).then(res =>{
      console.log(res);
      message.success('按钮添加成功')
      search()
    })
  }
  function onFinishFailedAddBtn(error) {
    console.log('error', error);
  }
  const onSelectAddBtn = (selectedKeys, info) => {
    console.log('selected', selectedKeys, info);
  };
  const onCheckAddBtn = (checkedKeys, info) => {
    setAddBtnId(checkedKeys.checked.join())
  };
  return (
    <>
    <Breadcrumb>
                <Breadcrumb.Item>系统主页</Breadcrumb.Item>
                <Breadcrumb.Item>
                    系统管理
                </Breadcrumb.Item>
                <Breadcrumb.Item>
                   菜单管理
                </Breadcrumb.Item>
            </Breadcrumb>

      {/* 头部   名称及日期搜索 */}
      <div style={{marginTop:20}}>
        <Form
          form={form}
          labelCol={{
            span: 4,
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
        >
          <Row>
            <Col span={8}>
              <Form.Item
                label="名称："
                name="menuName"
              >
                <Input />
              </Form.Item>
            </Col>
            <Col span={8}>
              <Form.Item
                label='创建时间：'
                name='createTime'
                style={{ marginRight: -500 }}
              >
                <RangePicker style={{ width: 400 }} />
              </Form.Item>
            </Col>
            <Col span={8} >
              <div style={{ textAlign: 'right' }}>
                <Button type="primary" htmlType="submit" size='middle'>
                  查询
                </Button>
                <Button size='middle' onClick={reset}>重置</Button>
              </div>
            </Col>
          </Row>
        </Form>
      </div>

      {/* 新增、删除及更多操作内容 */}
      <div>
        <Popconfirm title="请选择创建类型" okText="按钮"
          cancelText="菜单" okType='primary' onConfirm={confirm}
          onCancel={cancel}>
          <Button type='primary'>新增</Button>
        </Popconfirm>
        <Popconfirm
          title={`你确定要删除  ${delInfo.title}  这条数据吗`}
          onConfirm={() => delMenu(delInfo)}
          okText="是"
          cancelText="否"
        >
          <Button type='danger'>删除</Button>
        </Popconfirm>
        <Select
          defaultValue="更多操作"
          style={{
            width: 120,
          }}
          onChange={toExcel}
        >
          <Select.Option value='导出excel'>导出excel</Select.Option>
        </Select>
      </div>

      {/* 表格内容渲染 */}
      <div style={{ marginTop: 20 }}>
        <Space
          align="center"
          style={{
            marginBottom: 16,
          }}
        >
        </Space>
        <Table
          columns={columns}
          rowSelection={{
            ...rowSelection,
          }}
          dataSource={menuData}
          rowKey='id'
          scroll={{
            x: 1500,
          }}
          total={totalMenu}
        />
      </div>

      {/* 修改菜单抽屉 */}
      <Drawer title="修改菜单" onClose={onClose} open={open}
        footer={
          <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Select placeholder='树操作' showArrow={false} style={{ width: 100 }}>
              <Select.Option value='展开所有'>展开所有</Select.Option>
              <Select.Option value='合并所有'>合并所有</Select.Option>
            </Select>
            <Button type="primary" onClick={onClose}>
              点击关闭
            </Button>
          </Space>
        }
        maskClosable={false}
        closable={false}
      >
        <Form
          form={formEdit}
          onFinish={onFinishEdit}
          onFinishFailed={onFinishFailedEdit}
        >
          <Form.Item
            label='菜单名称：'
            name='menuName'
            rules={[
              { required: true, message: '请输入菜单名称' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='菜单URL：'
            name='path'
            rules={[
              { required: true, message: '请输入菜单名称' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='组件地址：'
            name='component'
            rules={[
              { required: true, message: '请输入组件地址' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='相关权限：'
            name='permission'
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='菜单图标：'
            name='icon'
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='菜单排序：'
            name='order'
          >
            <Input />
          </Form.Item>
          <div>
            上级菜单： <Tree
              checkable
              checkStrictly
              checkedKeys={parentId}
              onSelect={onSelect}
              onCheck={onCheck}
              treeData={menuTree}
            />
          </div>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>

      {/* 新增菜单抽屉 */}
      <Drawer title="新增菜单" placement="right" onClose={onCloseAddMenu} open={openAddMenu}
        footer={
          <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Select placeholder='树操作' showArrow={false} style={{ width: 100 }}>
              <Select.Option value='展开所有'>展开所有</Select.Option>
              <Select.Option value='合并所有'>合并所有</Select.Option>
            </Select>
            <Button type="primary" onClick={onCloseAddMenu}>
              点击关闭
            </Button>
          </Space>
        }
        maskClosable={false}
        closable={false}
      >
        <Form
          onFinish={onFinishAddMenu}
          onFinishFailed={onFinishFailedAddMenu}
        >
          <Form.Item
            label='菜单名称'
            name='menuName'
            rules={[
              { required: true, message: '请输入菜单名称' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='菜单URL'
            name='path'
            rules={[
              { required: true, message: '请输入菜单URL地址' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='组件地址'
            name='component'
            rules={[
              { required: true, message: '请输入菜单组件地址' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='相关权限'
            name='permission'
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='菜单图标'
            name='icon'
          >
            <Input placeholder='请点击右侧按钮选择图标' />
          </Form.Item>
          <Form.Item
            label='菜单排序'
            name='order'
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='上级菜单'
            name='parentId'
          >
            <Tree
              checkable
              checkStrictly
              // checkedKeys={addMenuId}
              onSelect={onSelectAddMenu}
              onCheck={onCheckAddMenu}
              treeData={treeAddMenu}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>

      {/* 新增按钮抽屉 */}
      <Drawer title="新增按钮" placement="right" onClose={onCloseAddBtn} open={openAddBtn}
        footer={
          <Space style={{ display: 'flex', justifyContent: 'space-between' }}>
            <Select placeholder='树操作' showArrow={false} style={{ width: 100 }}>
              <Select.Option value='展开所有'>展开所有</Select.Option>
              <Select.Option value='合并所有'>合并所有</Select.Option>
            </Select>
            <Button type="primary" onClick={onCloseAddBtn}>
              点击关闭
            </Button>
          </Space>
        }
        maskClosable={false}
        closable={false}
      >
        <Form
          onFinish={onFinishAddBtn}
          onFinishFailed={onFinishFailedAddBtn}
        >
          <Form.Item
            label='按钮名称'
            name='menuName'
            rules={[
              { required: true, message: '请输入按钮名称' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='相关权限'
            name='permission'
          >
            <Input />
          </Form.Item>
          <Form.Item
            label='上级菜单'
            name='parentId'
          >
            <Tree
              checkable
              checkStrictly
              // checkedKeys={addMenuId}
              onSelect={onSelectAddBtn}
              onCheck={onCheckAddBtn}
              treeData={treeAddBtn}
            />
          </Form.Item>
          <Form.Item
            wrapperCol={{
              offset: 8,
              span: 16,
            }}
          >
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </Drawer>
    </>
  )
}
